<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 小组列表 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" class="handle-del mr10" @click="makeTeam">创建小组</el-button>
                <!-- <el-button type="danger" class="handle-del mr10" @click="exitTeam">退出小组</el-button> -->
                <el-button type="primary" class="handle-del mr10" @click="myTeam">我的小组</el-button>
            </div>
            <el-table
                :data="tableData.filter((data) => !search || data.teamName.toLowerCase().includes(search.toLowerCase()))"
                :default-sort="{ prop: 'teamId', order: ' ascending' }"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column label="小队编号" sortable prop="teamId"> </el-table-column>
                <el-table-column label="队名" prop="teamName"></el-table-column>
                <el-table-column label="队员" prop="students" :formatter="studentFormatter"> </el-table-column>
                <el-table-column label="课题" prop="project" :formatter="projectFormatter"></el-table-column>
                <el-table-column label="指导老师" prop="project" :formatter="teacherFormatter"> </el-table-column>
                <el-table-column label="得分" sortable prop="score"> </el-table-column>
                <el-table-column align="center">
                    <template slot="header" slot-scope="scope">
                        <el-input v-model="search" size="mini" placeholder="输入组名搜索" />
                    </template>
                    <template slot-scope="scope" align="center">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">加入</el-button>
                        <!-- <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        > -->
                    </template>
                </el-table-column>
            </el-table>
<!--            <el-button type="primary" @click="textWeb()">测试</el-button>-->
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes,prev, pager, next,jumper"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    :page-sizes="[5, 10, 15, 20]"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 加入小组弹出框 -->
        <el-dialog title="你确定加入该组吗？" :visible.sync="editVisible" width="30%">
            <el-form :model="form" label-width="70px">
                <!-- <el-form-item label="组名:">
                    <el-input v-model="form.teamName"></el-input>
                </el-form-item> -->
                <p>组名: {{ form.teamName }}</p>
                <p>指导老师：{{ tName }}</p>
                <p>课题：{{ pName }}</p>
                <v-span
                    >队员: <v-span v-for="(studentName, index) in studentsName" :key="index"> {{ studentName.studentName }}</v-span></v-span
                >
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!--新建弹出框 -->
        <el-dialog title="新建小组" :visible.sync="AddVisible" width="30%">
            <el-form :model="addteam" label-width="70px">
                <el-form-item label="组名:">
                    <el-input v-model="addteam.teamName"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="AddVisible = false">取 消</el-button>
                <el-button type="primary" @click="AddTeam">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchData } from '../../api/index';
export default {
    // name: 'basetable',
    data() {
        return {
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 5
            },
            showExit: false,
            number: localStorage.getItem('ms_number'),
            hasTeam: localStorage.getItem('hasTeam'),
            studentsName: [],
            AddForm: [],
            pageList: [],
            pName: '',
            tName: '',
            tableData: [],
            search: '',
            multipleSelection: [],
            delList: [],
            AddVisible: false,
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            sendMessage: {
                sendID: '',
                receiveID: '',
                message: ''
            },
            addteam: {
                teamName: ''
            }
        };
    },
    created() {
        //this.$http.this.getData();
        this.$http({
            method: 'get',
            url: 'http://localhost:9900/team/findAll',
            headers: {
                token: this.number
            }
        }).then((res) => {
            //console.log(res.data);

            this.pageList = res.data;
            console.log(this.pageList);
            this.pageTotal = res.data.length;
            this.currentChangePage(this.pageList, 1);
        });
    },
    methods: {
        //我的小组
        myTeam() {
            if (this.hasTeam == 'null') {
                this.$message.error('您还未加入任何小组');
            } else {
                this.$router.push('/myteam');
            }
        },
        // // 获取 easy-mock 的模拟数据
        // getData() {
        //     fetchData(this.query).then((res) => {
        //         console.log(res);
        //         this.tableData = res.list;
        //         this.pageTotal = res.pageTotal || 50;
        //     });
        // },
        // 触发搜索按钮
        // handleSearch() {
        //     this.$set(this.query, 'pageIndex', 1);
        //     this.getData();
        // },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        //退出小组
        exitTeam() {
            if (this.hasTeam == 'null') {
                this.AddVisible = false;
                this.$message.error('您还未加入任何小组');
            } else {
                // 二次确认删除
                this.$confirm('确定要退出吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.get('http://localhost:9900/message/sendExitMessage?number=' + this.number).then((res) => {
                        console.log(res.data);
                        if (res.data != null) {
                            this.$message.error(res.data);
                        }
                        if (res.data == null) {
                            this.$message.success('申请成功，等待审核！');
                        }
                    });
                });
            }
        },
        makeTeam() {
            if (this.hasTeam != 'null') {
                this.AddVisible = false;
                this.$message.error('您已经有小组了！');
            } else {
                this.AddVisible = true;
            }
        },
        AddTeam() {
            this.$http({
                method: 'post',
                url: 'http://localhost:9900/team/addTeam',
                data: this.addteam,
                headers: {
                    token: this.number
                }
            }).then((res) => {
                this.AddVisible = false;
                console.log(res.data);
                this.$message.success('创建成功！');
            });

            // const length = this.multipleSelection.length;
            // let str = '';
            // this.delList = this.delList.concat(this.multipleSelection);
            // for (let i = 0; i < length; i++) {
            //     str += this.multipleSelection[i].name + ' ';
            // }
            // this.$message.error(`删除了${str}`);
            // this.multipleSelection = [];
        },
        // 加入操作
        handleEdit(index, row) {
            if (this.hasTeam != 'null') {
                this.AddVisible = false;
                this.$message.error('您已经有小组了！');
            } else {
                console.log(row);
                if (row.project == null) {
                    this.pName = '(暂无）';
                    this.tName = '(暂无）';
                } else {
                    this.pName = row.project.projectName;
                    this.tName = row.project.teacher.teacherName;
                }
                this.idx = index;
                this.studentsName = row.students;
                this.form = row;
                this.editVisible = true;
            }
        },
        // 保存编辑
        saveEdit() {
            console.log(this.form.teamId);
            console.log(this.number);
            this.$http.get('http://localhost:9900/team/joinTeam?teamId=' + this.form.teamId + '&number=' + this.number).then((res) => {
                console.log(res.data);
            });
            this.editVisible = false;

            this.$message.success(`申请加入成功，等待审核！ `);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(currentPage) {
            this.query.pageIndex = currentPage;
            this.currentChangePage(this.pageList, currentPage);
        },
        //改变每页条数
        handleSizeChange(pageSize) {
            this.query.pageSize = pageSize;
            this.handleCurrentChange(this.query.pageIndex);
        },
        handleCurrentChange(currentPage) {
            this.query.pageIndex = currentPage;
            this.currentChangePage(this.pageList, currentPage);
        },
        //分页显示
        currentChangePage(list, currenPage) {
            let from = (currenPage - 1) * this.query.pageSize; //0
            let to = currenPage * this.query.pageSize; //5
            this.tableData = []; //[]
            for (; from < to; from++) {
                if (list[from]) {
                    this.tableData.push(list[from]);
                }
            }
        },
        // //课题展示
        projectFormatter(row, column, cellValue) {
            if (cellValue == null) {
                return '';
            } else {
                return cellValue.projectName;
            }
        },
        // //老师展示
        teacherFormatter(row, column, cellValue) {
            if (cellValue == null) {
                return '';
            } else {
                return cellValue.teacher.teacherName;
            }
        },
        //学生展示
        studentFormatter(row, column, cellValue) {
            if (cellValue == null) {
                return '暂无';
            } else {
                var i = 0;
                var arr = [];
                for (i; i < cellValue.length; i++) {
                    arr.push(cellValue[i].studentName);
                    if (i != cellValue.length - 1) {
                        arr.push(',');
                    }
                }
                return arr;
            }
        },

        //测试web
        textWeb() {
            var websocket = null;
            if ('WebSocket' in window) {
                websocket = new WebSocket('ws://localhost:9900/TeamSocket/001/002');
                console.log('测试链接打开');
                websocket.onopen = function () {
                    console.log('链接打开！');
                    websocket.send('申请加入小组');
                };
                //收到消息事件
                websocket.onmessage = function (msg) {
                    console.log(msg);
                };
                //关闭链接
                websocket.onclose = function () {
                    console.log('链接关闭');
                };
                //发生了错误事件
                websocket.onerror = function () {
                    alert('Socket发生了错误');
                };

                //窗口关闭时，关闭连接
                window.unload = function () {
                    websocket.close();
                };
            }
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
